package com.lagou.handler;

import cn.hutool.core.util.StrUtil;
import com.lagou.service.IUserService;
import com.lagou.service.RpcRequest;
import com.lagou.service.RpcResult;
import com.lagou.service.UserServiceImpl;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.concurrent.EventExecutorGroup;
import org.apache.logging.log4j.spi.ObjectThreadContextMap;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;

import java.lang.reflect.Method;

/**
 * 自定义的业务处理器
 */
public class UserServiceHandler extends ChannelInboundHandlerAdapter{

    public UserServiceHandler(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    private ApplicationContext applicationContext;

    //当客户端读取数据时,该方法会被调用
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        RpcRequest rpcRequest = null;
        //1转换为标准协议对象
        if (msg != null) {
            rpcRequest = (RpcRequest) msg;
        }else {
            returnFailRst(ctx, "请求协议不能为空！！！");
            return;
        }

        //2根据协议对象调用具体的服务方法
        if (StrUtil.isNotBlank(rpcRequest.getRequestId())) {

            //2.1 从spring容器中获取对象
            Object bean = applicationContext.getBean(StrUtil.lowerFirst(rpcRequest.getRequestId()));

            //2.2 执行得到的对象的方法
            Method method = ReflectionUtils.findMethod(bean.getClass(), rpcRequest.getMethodName(), rpcRequest.getParameterTypes());
            Object result = ReflectionUtils.invokeMethod(method, bean, rpcRequest.getParameters());
            returnSuccessRst(ctx, result);
        }else {
            returnFailRst(ctx, "请求协议的请求对象的ID不能为空！！！");
        }
        return;
    }

    /**
     * 返回成功结果对象
     * @param data
     * @return
     */
    private void returnSuccessRst(ChannelHandlerContext ctx, Object data){
        RpcResult rpcResult = new RpcResult();
        rpcResult.setSuccess(true);
        rpcResult.setMessage("处理成功！！！");
        rpcResult.setData(data);
        ctx.writeAndFlush(rpcResult);
    }

    /**
     * 返回失败结果对象
     * @param msg 失败信息
     * @return
     */
    private void returnFailRst(ChannelHandlerContext ctx, String msg){
        RpcResult rpcResult = new RpcResult();
        rpcResult.setSuccess(false);
        rpcResult.setMessage("处理失败！！！" + msg);
        rpcResult.setData(null);
        ctx.writeAndFlush(rpcResult);
    }
}
